//
//  AppDelegate.m
//  KuWoCan
//
//  Created by hwd on 17/3/2.
//  Copyright © 2017年 hwd. All rights reserved.
//

#import "AppDelegate.h"
#import <AudioToolbox/AudioToolbox.h>
#import "LoginViewController.h"
#import "PushNotificationView.h"

#import "NewsViewController.h"
#import "MyViewController.h"
#import "NWLoginRequest.h"
#import "JKeyChainHelper.h"
#import "MBProgressHUD.h"

#import "HomeViewController.h"
//引导页
#import "GuideViewController.h"

extern NSString *const kJPFNetworkIsConnectingNotification; // 正在连接中
extern NSString *const kJPFNetworkDidSetupNotification;     // 建立连接
extern NSString *const kJPFNetworkDidCloseNotification;     // 关闭连接
extern NSString *const kJPFNetworkDidRegisterNotification;  // 注册成功
extern NSString *const kJPFNetworkDidLoginNotification;     // 登录成功
extern NSString *const kJPFNetworkDidReceiveMessageNotification;         // 收到消息(非APNS)
extern NSString *const kJPFServiceErrorNotification;  // 错误提示


@interface AppDelegate ()

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    //Required
    //notice: 3.0.0及以后版本注册可以这样写，也可以继续用之前的注册方式
    JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init];
    entity.types = JPAuthorizationOptionAlert|JPAuthorizationOptionBadge|JPAuthorizationOptionSound;
    [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];
    [NSUserDefaults saveBool:YES forkey:@"netEnvironment"];

    [UIApplication sharedApplication].applicationIconBadgeNumber = 0;

    // init Push
    // notice: 2.1.5版本的SDK新增的注册方法，改成可上报IDFA，如果没有使用IDFA直接传nil
    // 如需继续使用pushConfig.plist文件声明appKey等配置内容，请依旧使用[JPUSHService setupWithOption:launchOptions]方式初始化。
    [JPUSHService setupWithOption:launchOptions appKey:appKey
                          channel:channel
                 apsForProduction:isProduction
            advertisingIdentifier:nil];

    //JPush 监听登陆成功
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networkDidLogin:) name:kJPFNetworkDidLoginNotification object:nil];

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSLog(@"%@",documentsDirectory);
    if (![[NSUserDefaults retrieveObjectForKey:kNotFirstUseApp] boolValue])
    {//首次打开App
        [NSUserDefaults saveObject:@(YES) forKey:kNotFirstUseApp];
        GuideViewController *guideVC = [[GuideViewController alloc] init];
        guideVC.jumpGuideHandle = ^{
            [self showLoginNav];
        };
        self.window.rootViewController = [[UINavigationController alloc] initWithRootViewController:guideVC];
        //        [self showLoginNav];
    }else
    {
        UserModel *model = [UserModel getUser];

        if (model)
        {//已登录过
            [self loginWithUser:model];
        }
        else
        {//未登录过
            [self showLoginNav];
        }
    }

    [self initData];
    [self.window makeKeyAndVisible];
    return YES;
}

- (void)loginWithUser:(UserModel *)model {
    NSString *pd = [JKeyChainHelper getPasswordWithService:kwPasswordService];
    if (!model.loginName || !pd) {
        [self showLoginNav];
        return;
    }
    LoginViewController *loginVC = [[LoginViewController alloc]init];
    UINavigationController *nav  = [[UINavigationController alloc]initWithRootViewController:loginVC];
    self.window.rootViewController = nav;
    [loginVC autoLoginUserLoginName:model.loginName password:pd];
}

/**
 *  登录成功，设置别名，移除监听
 *
 */
- (void)networkDidLogin:(NSNotification *)notification {
    NSLog(@"已登录");
    NSString *kJPushTags = [Singleton shareInstance].userType;
    NSString *kJPushAlias = [Singleton shareInstance].userId;
    [JPUSHService setTags:[NSSet setWithArray:@[kJPushTags]] alias:kJPushAlias fetchCompletionHandle:^(int iResCode, NSSet *iTags, NSString *iAlias){
        NSLog(@"rescode: %d, \ntags: %@, \nalias: %@\n", iResCode, iTags, iAlias);
    }];

    [[NSNotificationCenter defaultCenter] removeObserver:self name:kJPFNetworkDidLoginNotification object:nil];
}


- (void)initData
{
    [[Singleton shareInstance] initializeApp:^(BOOL complete,NWInitializeVersionModel *model,BOOL showError) {
        if (!complete)
        {
            if (showError)
            {//第一次初始化失败 提示
                __weak typeof(self)weakSelf = self;
                UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"数据初始化失败，请重试" preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"重新加载" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    [weakSelf initData];
                } ];
                [alertController addAction:okAction];

            }

        }else
        {
//            if (model.appVersion.length > 0 && [model.appVersion compare:kVersion] == NSOrderedDescending )
//            {
//
//                NSLog(@"当前版本号为%@ 检测到新app版本%@",kVersion,model.appVersion);
//                model.isForceUpdate = YES;
//
//                UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"温馨提示" message:[NSString stringWithFormat:@"%@ 版本已发布，是否更新？",model.appVersion] preferredStyle:UIAlertControllerStyleAlert];
//                UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"立即更新" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//
//                    if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:model.downloadUrl]])
//                    {
//                        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:model.downloadUrl]];
//                    }
//
//                } ];
//                [alertController addAction:okAction];
//
//            }
        }
    }];

}


- (void)setRootViewController
{
    self.tabBarController=[self TabBar];
    self.window.rootViewController = self.tabBarController;

}

- (void)showLoginNav
{
    LoginViewController *loginVC = [[LoginViewController alloc]init];
    UINavigationController *nav  = [[UINavigationController alloc]initWithRootViewController:loginVC];
    self.window.rootViewController = nav;
}

-(CustomTabbarViewController*)TabBar
{
    NSArray * viewControllers=nil;
    //创建一个静态数组，并关联导航控制器
    CustomTabbarViewController* tabBarController = [[CustomTabbarViewController alloc]init];

    HomeViewController* homeController =[[HomeViewController alloc]init];
    MyViewController* myViewController =[[MyViewController alloc]init];
    NewsViewController* newsViewController = [[NewsViewController alloc]init];

    UINavigationController *newsNavController =[[UINavigationController alloc] initWithRootViewController:newsViewController];  //实例化导航控制器，并关联视图控制器
    UINavigationController *homeNavController =[[UINavigationController alloc] initWithRootViewController:homeController];
    UINavigationController *mineNavController = [[UINavigationController alloc] initWithRootViewController:myViewController];

    viewControllers = [NSArray arrayWithObjects:newsNavController,mineNavController,homeNavController,nil];
    //    newsNavController.tabbarViewController = tabBarController;
    //    homeNavController.tabbarViewController = tabBarController;
    //    mineNavController.tabbarViewController = tabBarController;

    tabBarController.arrayViewcontrollers = viewControllers;   //将导航控制器数组关联到tabBar
    //    [self.window addSubview:tabViewController.view];   //添加tabBar视图到window
    //设置默认
    [tabBarController touchBtnAtIndex:2];

    //tabBarController.delegate = self;
    CustomBarButton *barButton = [tabBarController.arrayBarButtons objectAtIndex:0];
    [barButton setBadgeValue:nil];

    return tabBarController;

}

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    /// Required - 注册 DeviceToken
    NSString *token = [[[[deviceToken description]
                         stringByReplacingOccurrencesOfString:@"<" withString:@""]
                        stringByReplacingOccurrencesOfString:@">" withString:@""]
                       stringByReplacingOccurrencesOfString:@" " withString:@""];


    NSLog(@"DeviceToken：\n----------\n%@\n-----------", token);
    [JPUSHService registerDeviceToken:deviceToken];

}

- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    //Optional
    NSLog(@"did Fail To Register For Remote Notifications With Error: %@", error);
}


#pragma mark- JPUSHRegisterDelegate

// iOS 10 Support
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler
{
    // Required
    NSDictionary * userInfo = notification.request.content.userInfo;
    if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
    }
    completionHandler(UNNotificationPresentationOptionAlert); // 需要执行这个方法，选择是否提醒用户，有Badge、Sound、Alert三种类型可以选择设置
}

// iOS 10 Support
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler
{
    // Required
    NSDictionary * userInfo = response.notification.request.content.userInfo;
    if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
    }
    completionHandler();  // 系统要求执行这个方法
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
{

    // Required, iOS 7 Support
    [JPUSHService handleRemoteNotification:userInfo];
    
    if (userInfo) {
        if (application.applicationState == UIApplicationStateInactive) {
            [UIApplication sharedApplication].applicationIconBadgeNumber -= 1;
        } else if (NSFoundationVersionNumber < NSFoundationVersionNumber_iOS_9_0) {
            AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
            AudioServicesPlaySystemSound(1007);
            PushNotificationView *messageView = [[PushNotificationView alloc] initWithFrame:CGRectMake(0, -64, SCREENW, 64) andDescription:userInfo[@"aps"][@"alert"]];
            [[UIApplication sharedApplication].keyWindow addSubview:messageView];
            [UIView animateWithDuration:0.4 animations:^{
                messageView.frame = CGRectMake(0, 0, SCREENW, 64);
            } completion:^(BOOL finished) {
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [UIView animateWithDuration:0.4 animations:^{
                        messageView.frame = CGRectMake(0, -64, SCREENW, 64);
                    } completion:^(BOOL finished) {
                        [messageView removeFromSuperview];
                    }];
                });
            }];
        }
        completionHandler(UIBackgroundFetchResultNewData);
    } else {
        completionHandler(UIBackgroundFetchResultNoData);
    }
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{

    // Required,For systems with less than or equal to iOS6
    [JPUSHService handleRemoteNotification:userInfo];
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}


@end
